﻿using Juli.Mes.Mqtt.Etos;
using Juli.Mes.Mqtt.Extensions;
using Juli.Mes.Mqtt.Topics;
using Microsoft.Extensions.Logging;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.EventBus.Distributed;

namespace Juli.Mes.Mqtt
{
    [ExposeServices(typeof(IMqttConnectionService), typeof(IMqttService))]
    public class MqttConnectionService : MqttServiceBase, IMqttConnectionService, ISingletonDependency
    {
        private readonly ILogger<MqttConnectionService> _logger;
        private readonly IDistributedEventBus _distributedEventBus;

        public MqttConnectionService(
            ILogger<MqttConnectionService> logger,
            IDistributedEventBus distributedEventBus)
            : base()
        {
            _logger = logger;
            _distributedEventBus = distributedEventBus;
        }

        public override void ConfigureMqttServer(MqttServer mqttServer)
        {
            base.ConfigureMqttServer(mqttServer);

            MqttServer.ValidatingConnectionAsync += ValidatingConnectionHandlerAsync; ;
            MqttServer.ClientConnectedAsync += ClientConnectedHandlerAsync;
            MqttServer.ClientDisconnectedAsync += ClientDisconnectedHandlerAsync;
        }

        private Task ValidatingConnectionHandlerAsync(ValidatingConnectionEventArgs eventArgs)
        {
            // TODO:检查设备
            // 无效客户端：if(context.ClientId != deviceId) context.ReasonCode = MQTTnet.Protocol.MqttConnectReasonCode.ClientIdentifierNotValid; // id不对
            // 用户名和密码不对：MQTTnet.Protocol.MqttConnectReasonCode.BadUserNameOrPassword;
            // 没有权限：        MQTTnet.Protocol.MqttConnectReasonCode.NotAuthorized;
            // ？？？：          MqttConnectReasonCode.UnspecifiedError;

            if (eventArgs.ClientId == "SpecialClient")
            {
                if (eventArgs.UserName != "USER" || eventArgs.Password != "PASS")
                {
                    eventArgs.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                }
            }

            return Task.CompletedTask;
        }

        private async Task ClientConnectedHandlerAsync(ClientConnectedEventArgs eventArgs)
        {
            MqttServer.PublishByHub(BrokerTopics.Event.NewClientConnected, eventArgs.ClientId);

            await _distributedEventBus.PublishAsync(
               new ClientConnectedEto
               {
                   ClientId = eventArgs.ClientId
               }
            );
        }

        private async Task ClientDisconnectedHandlerAsync(ClientDisconnectedEventArgs eventArgs)
        {
            MqttServer.PublishByHub(BrokerTopics.Event.NewClientDisconnected, eventArgs.ClientId);

            await _distributedEventBus.PublishAsync(
               new ClientDisconnectedEto
               {
                   ClientId = eventArgs.ClientId
               }
            );
        }
    }
}
